﻿using com.tanlingyun.baojia.Entity;
using com.tanlingyun.ViewModel;
using FluentData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.tanlingyun.DbServices
{
    /// <summary>
    /// 产品
    /// </summary>
    public class ProductService:BaseService
    {
        /// <summary>
        /// 获取产品列表
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="search"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public PageInfo<Products> plist(int user_id,string search = "",int PageIndex = 1,int PageSize= 10,int manager_id = 0)
        {
            PageInfo<Products> pdlist = new PageInfo<Products>()
            {
                Fields = "*",
                TableName = "Products",
                PageIndex = PageIndex,
                PageSize = PageSize,
                OrderBy = "ID desc"
            };

            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return pdlist;

            string where = "status=1 ";
            if (entityUser.level_type == (int)ELevelType.Operator)
                where += " and manager_id=" + entityUser.parentid;
            else if (entityUser.level_type == (int)ELevelType.Admin)
                where += " and manager_id=" + manager_id;
            else
                where += " and manager_id=" + entityUser.id;

            if (!string.IsNullOrWhiteSpace(search)) ;
            
            //if (entityUser.level_type == (int)ELevelType.Operator)
            //    where += " and add_user=" + user_id;

            pdlist.Where = where;
            return GetPageInfo<Products>(pdlist);
        }

        /// <summary>
        /// 产品汇总
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="search"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public PageInfo<V_ProductSummary> psummarylist(int user_id, string search = "", int PageIndex = 1, int PageSize = 10,int manager_id = 0)
        {
            PageInfo<V_ProductSummary> pspage = new PageInfo<V_ProductSummary>() { PageIndex = PageIndex,PageSize = PageSize };
            PageInfo<Products> ppage = plist(user_id, search, PageIndex, PageSize, manager_id);
            pspage.TotalCount = ppage.TotalCount;
            pspage.TotalPage = ppage.TotalPage;
            
            if(ppage.List.Count()>0)
            {
                UserService _userService = new UserService();
                IList<V_ProductSummary> splist = new List<V_ProductSummary>();
                foreach (var item in ppage.List)
                {
                    V_ProductSummary ps = new V_ProductSummary() {
                        Name = item.Name,
                        Sno = item.Sno,
                        ID = item.ID,
                        addtime = item.addtime,
                        add_user = item.add_user,
                        Customer = item.Customer,
                        FinishTime = item.FinishTime,
                        IsFinished = item.IsFinished,
                        OrderNo = item.OrderNo,
                        Status = item.Status    
                    };
                    User entityUser = _userService.GetUser(ps.add_user);
                    if (entityUser != null)
                        ps.Operator = entityUser.name;
                    splist.Add(ps);
                }
                pspage.List = splist;
            }
            return pspage;
        }

        /// <summary>
        /// 零件列表(搜索零件)
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="search"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public PageInfo<Parts> Partlist(int user_id,string search="",int PageIndex = 1,int PageSize= 10,int manager_id = 0)
        {
            PageInfo<Parts> partpage = new PageInfo<Parts>() { Fields = "*", TableName = "Parts", PageIndex = PageIndex, PageSize = PageSize, OrderBy = "ID desc" };

            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return partpage;

            string where = "status=1 ";
            if (entityUser.level_type == (int)ELevelType.Operator)
                where += " and manager_id=" + entityUser.parentid;
            else if (entityUser.level_type == (int)ELevelType.Admin)
                where += " and manager_id=" + manager_id;
            else
                where += " and manager_id=" + entityUser.id;

            if (!string.IsNullOrWhiteSpace(search))
                where += " and Sno like '%" + search + "%' or Name like '%" + search + "%'";
            partpage.Where = where;
            return GetPageInfo<Parts>(partpage);
        }

        public OperateResult AddProduct(int user_id,Products pd)
        {
            Products entityProduct = GetProduct(pd.Sno);
            if (entityProduct != null && entityProduct.Status == 1)
                return new OperateResult() { code = ResultCode.Failed,message = string.Format("产品编号{0}已经存在！",pd.Sno) };

            //验证用户信息
            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户信息错误，请重新登录！" };
            if (entityUser.level_type == (int)ELevelType.Admin)
                pd.manager_id = 0;
            else if (entityUser.level_type == (int)ELevelType.Manager)
                pd.manager_id = entityUser.id;

            pd.add_user = user_id;
            pd.addtime = DateTime.Now;
            pd.Status = 1;

            if (db.Insert<Products>("Products", pd).AutoMap(x => x.ID).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed,message = "产品添加失败！" };
        }
        
        /// <summary>
        /// 获取产品 零件分页
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <param name="parent_id">父级零件编号，获取该零件下的所有零件</param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public PageInfo<V_ProductPart> GetProductPartPage(int user_id,int product_id,int parent_id = 0,int PageIndex = 1,int PageSize = 10,int manager_id = 0)
        {
            PageInfo<V_ProductPart> vpppage = new PageInfo<V_ProductPart>() {
                Fields  = "parts.ID as part_id,productpart.ID as pp_id,productpart.product_id,parts.Sno,parts.Name,productpart.qty,productpart.weight",
                TableName = "productpart left JOIN parts on productpart.part_id = parts.ID",
                PageIndex = PageIndex,
                PageSize = PageSize,
                OrderBy = "ProductPart.ID desc"
            };

            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return vpppage;

            string where = "1=1 ";
            if (entityUser.level_type == (int)ELevelType.Operator)
                where += " and parts.manager_id=" + entityUser.parentid;
            else if (entityUser.level_type == (int)ELevelType.Admin)
                where += " and parts.manager_id=" + manager_id;
            else
                where += " and parts.manager_id=" + entityUser.id;

            where += " and productpart.status=1 and productpart.product_id=" + product_id + " and parent_id=" + parent_id;
            vpppage.Where = where;
            return GetPageInfo<V_ProductPart>(vpppage);
        }

        /// <summary>
        /// 为产品添加零件
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="productid"></param>
        /// <param name="part"></param>
        /// <returns></returns>
        public OperateResult AddPart(int user_id, int productid,int parent_part_id, Parts part)
        {
            //Parts entityPart = GetPart(part.Sno);
            //if (entityPart != null && entityPart.status == 1)
            //    return new OperateResult() { code = ResultCode.Failed, message = string.Format("零件编号{0}已存在，不能进行重复添加！", part.Sno) };
            Products entityProduct = GetProduct(productid);
            if (entityProduct == null || entityProduct.Status != 1)
                return new OperateResult() { code = ResultCode.Failed,message = string.Format("产品编号{0}不存在！",productid) };

            //验证用户信息
            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户信息错误，请重新登录！" };

            if (entityUser.level_type == (int)ELevelType.Admin)
                part.manager_id = 0;
            else
            {
                if (entityUser.level_type == (int)ELevelType.Manager)
                {
                    part.manager_id = entityUser.id;
                    if (entityProduct.manager_id != entityUser.id)
                        return new OperateResult() { code = ResultCode.Failed,message = "无法操作其他管理员的数据！" };
                }
                else
                {
                    part.manager_id = entityUser.parentid;
                    if(entityProduct.manager_id!=entityUser.parentid)
                        return new OperateResult() { code = ResultCode.Failed, message = "无法操作其他管理员的数据！" };
                }
            }

            part.add_time = DateTime.Now;
            part.add_user = user_id;
            part.status = 1;

            part.ID = db.Insert<Parts>("Parts", part).AutoMap(x => x.ID).ExecuteReturnLastId<int>();
            if(part.ID>0)
            {
                return AddProductPart(user_id, productid, part.ID, parent_part_id);
            }
            return new OperateResult() { code = ResultCode.Failed,message = "零件添加失败！" };
        }

        /// <summary>
        /// 给产品添加零件
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <param name="part_id"></param>
        /// <param name="parent_part_id"></param>
        /// <returns></returns>
        public OperateResult AddProductPart(int user_id, int product_id, int part_id, int parent_part_id = 0)
        {
            Products entityProduct = GetProduct(product_id);
            if (entityProduct == null || entityProduct.Status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品编号{0}不存在！", product_id) };
            Parts entityPart = GetPart(part_id);
            if (entityPart == null || entityPart.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("零件编号{0}不存在！", part_id) };



            if (parent_part_id > 0)
            {
                ProductPart pp = GetProductPart(parent_part_id);
                if (pp == null || pp.status != 1)
                    return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品零件编号{0}不存在！", parent_part_id) };
            }

            ProductPart pt = GetProductPart(product_id, part_id, parent_part_id);
            if (pt == null)
            {
                pt = new ProductPart()
                {
                    operator_time = DateTime.Now,
                    operator_user = user_id,
                    product_id = product_id,
                    part_id = part_id,
                    qty = 1,
                    status = 1,
                    weight = 0,
                    parent_id = parent_part_id
                };
                if (db.Insert<ProductPart>("ProductPart", pt).AutoMap(x => x.ID).Execute() > 0)
                    return new OperateResult() { code = ResultCode.Success };
            }
            else
            {
                pt.qty++;
                pt.operator_user = user_id;
                pt.operator_time = DateTime.Now;
                if (db.Update<ProductPart>("ProductPart", pt).Column(x => x.qty).Where(x => x.ID).Execute() > 0)
                    return new OperateResult() { code = ResultCode.Success };
            }

            return new OperateResult() { code = ResultCode.Failed };
        }

        public OperateResult AddPartMaterial(int user_id,PartMaterials PartMaterial)
        {
            //验证产品
            Products entityProduct = GetProduct(PartMaterial.product_id);
            if (entityProduct == null || entityProduct.Status != 1 /*|| entityProduct.add_user != user_id*/)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品编号{0}不存在！", PartMaterial.product_id) };
            //验证零件
            Parts entityParts = GetPart(PartMaterial.part_id);
            if (entityParts == null || entityParts.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("零件编号{1}不存在",entityParts.ID) };
            //验证产品零件
            ProductPart pd = GetProductPart(PartMaterial.pp_id);
            if (pd == null || pd.status != 1 || pd.part_id != PartMaterial.part_id)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("零件编号{1}不存在", PartMaterial.pp_id) };

            //验证原材料
            RawService _rawService = new RawService();
            RawMaterials entityRaw = _rawService.GetRaw(PartMaterial.raw_id);
            if (entityRaw == null || entityRaw.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("原材料编号{0}不存在！", PartMaterial.raw_id) };

            if (PartMaterial.qty <= 0)
                return new OperateResult() { code = ResultCode.Failed, message = "下单数量不能低于1！" };

            PartMaterial.add_time = DateTime.Now;
            PartMaterial.add_user = user_id;
            PartMaterial.status = 1;

            switch (PartMaterial.type)
            {
                case (int)EMaterialModel.Panel:
                    if (PartMaterial.p1 <= 0 || PartMaterial.p2 <= 0 || PartMaterial.p3 <= 0)
                        return new OperateResult() { code = ResultCode.Failed, message = "板料长宽厚信息错误！" };
                    //计算价格
                    //长*宽*厚 * 密度 (g*cm3)
                    double v = (PartMaterial.p1 * PartMaterial.p2 * PartMaterial.p3) / 1000; //mm3 => cm3
                    PartMaterial.weight = Math.Round(v * entityRaw.bizhong / 1000, 3);  //g=>kg
                    break;
                case (int)EMaterialModel.Bar:
                    if (PartMaterial.p1 <= 0 || PartMaterial.p2 <= 0)
                        return new OperateResult() { code = ResultCode.Failed,message = "棒料直径和长度信息错误！" };
                    //pi*(直径/2)平方 * 长度 * 密度
                    PartMaterial.weight = Math.Round((Math.PI * Math.Pow(PartMaterial.p2 / 2, 2) * PartMaterial.p2) / 1000 * entityRaw.bizhong / 1000, 3);
                    break;
                case (int)EMaterialModel.Tube:
                    if (PartMaterial.p1 <= 0 || PartMaterial.p2 <= 0 || PartMaterial.p3 <= 0)
                        return new OperateResult() { code = ResultCode.Failed, message = "圆管料外径内径长度信息错误！" };
                    //pi * ((外径-内径)/2)平方 * 长度 * 密度
                    PartMaterial.weight = Math.Round(Math.PI * PartMaterial.p3 * (Math.Pow(PartMaterial.p1 / 2, 2) - Math.Pow(PartMaterial.p2 / 2, 2)) / 1000 * entityRaw.bizhong / 1000, 3);
                    break;
                case (int)EMaterialModel.SquareSteelTube:
                    if (PartMaterial.p1 <= 0 || PartMaterial.p2 <= 0 || PartMaterial.p3 <= 0 || PartMaterial.p4<0)
                        return new OperateResult() { code = ResultCode.Failed, message = "方管料长宽高长度信息错误！" };
                    //(外底面积 - 内低面积) * 长度 
                    PartMaterial.weight = Math.Round((PartMaterial.p1 * PartMaterial.p2 - (PartMaterial.p1 - PartMaterial.p3) * (PartMaterial.p2 - PartMaterial.p3)) * PartMaterial.p4 / 1000 * entityRaw.bizhong / 1000, 3); 
                    break;
                case (int)EMaterialModel.SpecialSteel:
                    break;
                case (int)EMaterialModel.Other:

                    break;
                default:
                    break;
            }
            PartMaterial.price = Math.Round((decimal)PartMaterial.weight * entityRaw.price, 2);
            PartMaterial.total_price = PartMaterial.price * PartMaterial.qty;
            if (PartMaterial.tfl_weight > 0)
            {
                PartMaterial.total_price = PartMaterial.total_price - Math.Round((decimal)PartMaterial.tfl_weight * entityRaw.tfl_price * PartMaterial.qty, 2);
            }

            if (db.Insert<PartMaterials>("PartMaterials", PartMaterial).AutoMap(x => x.ID).Execute() > 0)
            {
                //更新零件信息
                db.Sql("update productpart set weight = (select sum(partmaterials.qty * partmaterials.weight) from partmaterials where pp_id = @0 and productpart.status = 1) where ID=@0", PartMaterial.pp_id).Execute();

                UpdateProductPrice(user_id, PartMaterial.product_id);

                return new OperateResult() { code = ResultCode.Success };
            }
            return new OperateResult() { code = ResultCode.Failed, message = "添加失败！" };
        }

        public IList<V_ProductTree_Part> GetProductPart(int product_id,int parent_id = 0)
        {
            return db.Sql("SELECT productpart.ID as pp_id, parts.ID,parts.Sno,parts.Name from productpart left JOIN parts on productpart.part_id = parts.ID where productpart.product_id=@0 and productpart.status=1 and productpart.parent_id=@1", product_id,parent_id).QueryMany<V_ProductTree_Part>();
        }
        /// <summary>
        /// 获取产品零件
        /// </summary>
        /// <param name="product_id"></param>
        /// <param name="part_id"></param>
        /// <returns></returns>
        public ProductPart GetProductPart(int id)
        {
            return db.Sql("select * from ProductPart where ID=@0", id).QuerySingle<ProductPart>();
        }
        /// <summary>
        /// 获取产品零件
        /// </summary>
        /// <param name="product_id"></param>
        /// <param name="part_id"></param>
        /// <param name="parent_part_id"></param>
        /// <returns></returns>
        public ProductPart GetProductPart(int product_id,int part_id,int parent_part_id)
        {
            return db.Sql("select * from ProductPart where product_id=@0 and part_id=@1 and parent_id=@2",product_id,part_id,parent_part_id).QuerySingle<ProductPart>();
        }

        public IList<V_ProductTree> GetProductTree(int user_id,int product_id = 0)
        {
            IList<V_ProductTree> tree = new List<V_ProductTree>();

            PageInfo<Products> pdpage = plist(user_id, "", 1, int.MaxValue);
            
            foreach (Products pd in pdpage.List)
            {
                V_ProductTree tr = new V_ProductTree() {
                    name = pd.Name,
                    sno = pd.Sno,
                    product_id = pd.ID,
                    IsFinished = pd.IsFinished
                };
                //获取产品零件
                tr.Parts = GetChildPart(tr.product_id, 0);

                tree.Add(tr);
            }
            return tree;
        }

        public IList<V_ProductTree_Part> GetChildPart(int product_id,int productpart_id)
        {
            IList < V_ProductTree_Part > parts  = new List<V_ProductTree_Part>();
            parts = GetProductPart(product_id, productpart_id);
            if(parts!=null && parts.Count>0)
            {
                foreach (var item in parts)
                {
                    item.childs = GetChildPart(product_id, item.pp_id);
                }
            }
            return parts;
        }

        

        /// <summary>
        /// 复制产品
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <param name="newProduct"></param>
        /// <returns></returns>
        public OperateResult CopyProduct(int user_id,int product_id,Products newProduct)
        {
            Products entityProduct = GetProduct(product_id);
            if (entityProduct == null || entityProduct.Status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品编号{0}不存在!", product_id) };
            using (IDbContext newdb = db.UseTransaction(true))
            {
                try
                { 
                    newProduct.addtime = DateTime.Now;
                    newProduct.add_user = user_id;
                    newProduct.material_price = entityProduct.material_price;
                    newProduct.price = entityProduct.price;
                    newProduct.ProcessingFees = entityProduct.ProcessingFees;
                    newProduct.Profit = entityProduct.Profit;
                    newProduct.Status = entityProduct.Status;

                    newProduct.ID = newdb.Insert<Products>("Products", newProduct).AutoMap(x => x.ID).ExecuteReturnLastId<int>();
                    if (newProduct.ID <= 0)
                    {
                        newdb.Rollback();
                        return new OperateResult() { code = ResultCode.Failed,message = "产品复制失败!" };
                    }
                    //复制产品零件
                    IList<ProductPart> partlist = newdb.Sql("select * from ProductPart where product_id=@0 and status=1", product_id).QueryMany<ProductPart>();
                    foreach (var item in partlist)
                    {
                        item.product_id = newProduct.ID;
                        item.operator_time = DateTime.Now;
                        item.operator_user = user_id;
                        item.ID = newdb.Insert<ProductPart>("ProductPart", item).AutoMap(x => x.ID).ExecuteReturnLastId<int>();
                        if(item.ID<=0)
                        {
                            newdb.Rollback();
                            return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品编号{0}零件{1}复制失败!", product_id, item.part_id) };
                        }
                    }

                    //复制产品零件工序

                    //复制零件材料

                    newdb.Commit();
                    return new OperateResult() { code = ResultCode.Success };
                }
                catch(Exception ex)
                {
                    newdb.Rollback();
                }
            }
            return new OperateResult() { code = ResultCode.Failed,message = "产品复制失败!" };
        }

        /// <summary>
        /// 完成产品录入
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public OperateResult IsFinishPD(int user_id,int product_id)
        {
            Products entityProduct = GetProduct(product_id);
            if (entityProduct == null || entityProduct.Status != 1)
                return new OperateResult() { code = ResultCode.Failed,message = string.Format("产编号{0}不存在！",product_id) };
            if (entityProduct.IsFinished == 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品\"{0}\"已经录入！", entityProduct.Name) };
            entityProduct.IsFinished = 1;

            if (db.Update<Products>("Products", entityProduct).Column(x => x.IsFinished).Where(x => x.ID).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };

            return new OperateResult() { code = ResultCode.Failed,message = "完成产品失败！" };
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <param name="pp_id"></param>
        /// <returns></returns>
        public OperateResult DeleteItem(int user_id,int product_id,int pp_id)
        {
            if (product_id == 0) return new OperateResult() { code = ResultCode.Failed,message = "未获取到产品信息！" };
            Products entityProduct = GetProduct(product_id);
            if (entityProduct == null || entityProduct.Status != 1)
                return new OperateResult() { code = ResultCode.Failed,message  = "删除的产品不存在！"};


            if(pp_id != 0)
            {
                ProductPart pp = GetProductPart(pp_id);
                if (pp == null || pp.status != 1)
                    return new OperateResult() { code = ResultCode.Failed,message = "删除的零件不存在！" };
                
                pp.status = 0;

                if (db.Update<ProductPart>("ProductPart", pp).Column(x => x.status).Where(x => x.ID).Execute() > 0)
                {
                    db.Sql("update ProductPart set status=0 where parent_id=@0", pp_id).Execute();
                    return new OperateResult() { code = ResultCode.Success };
                }
            }else
            {
                entityProduct.Status = 0;
                if (db.Update<Products>("Products", entityProduct).Column(x => x.Status).Where(x => x.ID).Execute() > 0)
                    return new OperateResult() { code = ResultCode.Success };
            }

            return new OperateResult() { code = ResultCode.Failed,message  = "删除失败！" };
        }


        /// <summary>
        /// 获取产品所有零件
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public IList<V_PartMaterial> GetPartMaterial(int user_id,int product_id)
        {
            return db.Sql("SELECT partmaterials.ID,parts.Sno as Part_sno,parts.Name as Part_name,rawmaterials.name as Raw_name,rawmaterials.guige as Raw_guige,partmaterials.qty,partmaterials.price,partmaterials.weight*partmaterials.qty as TotalWeight,partmaterials.total_price as TotalPrice from partmaterials left join parts on partmaterials.part_id = parts.ID left join rawmaterials on rawmaterials.id = partmaterials.raw_id where parts.status=1 and partmaterials.status=1 and partmaterials.product_id=@0", product_id).QueryMany<V_PartMaterial>();
        }

        /// <summary>
        /// 获取零件原材料
        /// </summary>
        /// <param name="pm_id">原材料编号</param>
        /// <returns></returns>
        public PartMaterials GetPartMaterial(int pm_id)
        {
            return db.Sql("select * from PartMaterials where ID=@0", pm_id).QuerySingle<PartMaterials>();
        }

        /// <summary>
        /// 获取零件材料
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <param name="part_id"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public PageInfo<V_PartMaterial> GetPartMaterial(int user_id, int product_id, int part_id, int pp_id = 0, int PageIndex = 1, int PageSize = 10)
        {
            PageInfo<V_PartMaterial> pmpage = new PageInfo<V_PartMaterial>()
            {
                Fields = "partmaterials.ID,parts.Sno as Part_sno,parts.Name as Part_name,rawmaterials.name as Raw_name,rawmaterials.guige as Raw_guige,partmaterials.qty,partmaterials.price,partmaterials.weight*partmaterials.qty as TotalWeight,partmaterials.total_price as TotalPrice",
                TableName = "partmaterials left join parts on partmaterials.part_id = parts.ID left join rawmaterials on rawmaterials.id = partmaterials.raw_id",
                PageIndex = PageIndex,
                PageSize = PageSize,
                OrderBy = "partmaterials.ID desc",
            };
            string where = "parts.status=1 and partmaterials.status=1 and partmaterials.product_id=" + product_id + " and partmaterials.part_id=" + part_id + " and partmaterials.pp_id=" + pp_id;
            pmpage.Where = where;
            return GetPageInfo<V_PartMaterial>(pmpage);
        }


        public Products GetProduct(string sno)
        {
            return db.Sql("select * from Products where Sno=@0",sno).QuerySingle<Products>();
        }

        public Products GetProduct(int product_id)
        {
            return db.Sql("select * from Products where ID=@0", product_id).QuerySingle<Products>();
        }

        public Parts GetPart(string Sno)
        {
            return db.Sql("select * from Parts where Sno=@0", Sno).QuerySingle<Parts>();
        }

        public Parts GetPart(int part_id)
        {
            return db.Sql("select * from Parts where ID=@0", part_id).QuerySingle<Parts>();
        }


        public OperateResult UpdateProductPrice(int user_id,int product_id)
        {
            Products entityProduct = GetProduct(product_id);
            if (entityProduct == null || entityProduct.Status != 1)
                return new OperateResult() { code  = ResultCode.Failed,message = "产品不存在！" };

            using (IDbContext newdb = db.UseTransaction(true))
            {
                try
                {
                    //统计单件材料费
                    newdb.Sql("UPDATE products set material_price =(select ifnull(SUM(total_price),0) from partmaterials where product_id=products.ID and status=1) where status=1 and products.ID=@0", product_id).Execute();
                    //统计单件工序费用
                    newdb.Sql("update products set processingFees = (select ifnull(sum(totalFee),0) from partgx where product_id=products.ID and status=1)+(select ifnull(sum(totalFee), 0) from materialgx where product_id = products.ID and status = 1) where products.ID = @0", product_id).Execute();
                    //统计单件总重量
                    newdb.Sql("update products set weight = ( select ifnull(sum(qty*weight),0) from productpart where product_id=products.ID and status=1) where products.ID=@0", product_id).Execute();
                    //计算产品价格
                    newdb.Sql("update products set price= material_price+ProcessingFees where ID=@0", product_id).Execute();

                    Products pd = newdb.Sql("select * from Products where ID=@0", product_id).QuerySingle<Products>();
                    if (pd == null) newdb.Rollback();
                    //计算产品利润
                    //1.材料与工时合计成本
                    //2.产品数量
                    //3.材料占成本比值
                    ProfitSetting setting = newdb.Sql("SELECT * from profitsetting where @0 BETWEEN MateTimeFr and MateTimeTo and @1 BETWEEN PdMonQtyFr and PdMonQtyTo and @2 BETWEEN MatRatioFr and MatRatioTo", pd.price, 1, Math.Round(pd.material_price / pd.price, 4)).QuerySingle<ProfitSetting>();
                    if (setting != null)
                    {
                        newdb.Sql("update products set profit=@0 where ID=@1", setting.Profit, product_id).Execute();
                    }
                    //新增一条历史记录
                    PriceRecords prd = new PriceRecords() {
                        material_price = pd.material_price,
                        price = pd.price,
                        ProcessingFees = pd.ProcessingFees,
                        operator_time = DateTime.Now,
                        operator_user = user_id,
                        product_id = pd.ID,
                        Profit = pd.Profit
                    };

                    newdb.Insert<PriceRecords>("PriceRecords", prd).AutoMap(x => x.ID).Execute();

                    newdb.Commit();
                    return new OperateResult() { code = ResultCode.Success };
                }
                catch(Exception ex)
                {
                    newdb.Rollback();
                    return new OperateResult() { code = ResultCode.Failed,message ="产品价格更新失败！" };
                }
            }
            return new OperateResult() { code = ResultCode.Failed };
        }
        

        
    }
}
